﻿using Grpc.Core;
using Newtonsoft.Json;
using SharedKernel.Infrastructure.Comm;

namespace ApiGateway.Middlewares
{
    public class GlobalExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
        private readonly IWebHostEnvironment _env;

        public GlobalExceptionHandlerMiddleware(
            RequestDelegate next,
            ILogger<GlobalExceptionHandlerMiddleware> logger,
            IWebHostEnvironment env)
        {
            _next = next;
            _logger = logger;
            _env = env;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            { 
                await _next(context);
            }
            catch (RpcException rpcEx)
            {
                _logger.LogError(rpcEx, $"----------------------------------------gRPC异常{DateTime.Now}-------------------------------------");
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(ResponseInfo<string>.Fail("RPC异常，请联系管理员", rpcEx.Status.Detail)));
            }
            catch (Exception ex)
            { 
                _logger.LogError(ex, $"----------------------------------------系统未捕获异常{DateTime.Now}-------------------------------------"); 
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(ResponseInfo<string>.Fail("系统异常，请联系管理员", ex.Message)));
            }
        }


    }
}
